const Router = require("koa-router");
const fs = require("fs");
const view = require("koa-views");
const Koa = require("koa");
const koaBody = require("koa-body");
let router = new Router();
let app = new Koa();
app.use(koaBody({ multipart:true}));
app.use(view(__dirname+'/zuoye/view'))
router.get('/index', async ctx => {
    await ctx.render('index.html')
})
router.post("/php/add.php", ctx => {
    // let tempath = ctx.request.body;
    let getimg = ctx.request.files.myimg.filepath;
    let filename = ctx.request.files.myimg.originalFilename;
    //创建一个文件夹存放图片
    fs.copyFileSync(getimg, "./zuoye/cssjs/img/" + filename);
    let fileurl = "./img/" + filename;
    let newObj = { ...ctx.request.body, fileurl };
    if (!fs.existsSync("./zuoye/cssjs/data.json")) {
        //没有存储的时候直接存入数据
        fs.writeFileSync("./zuoye/cssjs/data.json", JSON.stringify([newObj]));
    } else {
        let data = JSON.parse(fs.readFileSync("./zuoye/cssjs/data.json"));
        data.push(newObj);
        fs.writeFileSync("./zuoye/cssjs/data.json", JSON.stringify(data))
    }
    ctx.body={info:"接收了"}
})
app.use(router.routes());
app.listen(8686);